package com.quasar.hpatient.view.personal.historyRecord;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.choicePhoto.PhotoSelectorActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.controllermodel.PictureConstant;
import com.quasar.hpatient.model.custommodel.PhotoModel;
import com.quasar.hpatient.model.event.DeletePhotoEvent;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.Aerainfodb;
import com.quasar.hpatient.model.litePalmodel.HospitalInfodb;
import com.quasar.hpatient.model.medicalmodel.CaseinformationData;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.onInterface.OnCaseHistoryListener;
import com.quasar.hpatient.presenter.CaseHistoryPresenter;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.DeletePhotoActivity_;
import com.quasar.hpatient.view.adapter.MyGrideViewAdapter;
import com.quasar.hpatient.widget.AutoHeightGridView;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import me.iwf.photopicker.PhotoPicker;

/**
 * 添加病例
 */
@OptionsMenu(R.menu.menu_submit)
@EActivity(R.layout.activity_add_case)
public class AddCaseActivity extends BaseActivity implements OnCaseHistoryListener, PictureConstant.updateUiInit {

    private CaseHistoryPresenter caseHistoryPresenter;
    MyGrideViewAdapter myGrideViewAdapter;
    //保存当如化验单图片
    public static ArrayList<PhotoModel> minitDatas = new ArrayList();
    PictureConstant pictureConstant;
    @Extra
    CaseinformationData caseinformationData;
    //获取地理信息
    List<Aerainfodb> Geography = new ArrayList<>();
    private List<List<HospitalInfodb>> screenHospitalList = new ArrayList<>();
    /**
     * 医院筛选
     */
    List<HospitalInfodb> hospitalInfoDBList = MainAppliaction.getInstance().getHospitalInfodbList();
    //记录医院id
    int HospitalId = 0;

    //病例标题
    @ViewById(R.id.et_case_title)
    EditText et_case_title;
    //医院名称
    @ViewById(R.id.tv_hospital_title)
    TextView tv_hospital_title;
    @ViewById(R.id.tv_time)
    TextView tv_time;
    @ViewById(R.id.st_miaoshu)
    EditText st_miaoshu;
    @ViewById(R.id.gridView)
    AutoHeightGridView gridView;

    @AfterViews
    void init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initView();
        initData();
    }

    @Override
    protected void initView() {
        initToolbar();
        pictureConstant = new PictureConstant(this);
        myGrideViewAdapter = new MyGrideViewAdapter(this, minitDatas);
        gridView.setAdapter(myGrideViewAdapter);
        caseHistoryPresenter = new CaseHistoryPresenter(this);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == minitDatas.size()) {
                    isdelete=false;
                    selectPic();
                } else {
                    //跳转图片预览界面
                    //传递标识显示隐藏删除图片按钮
                    DeletePhotoActivity_.intent(AddCaseActivity.this).position(position).photoModelDatas(minitDatas).start();
                }

            }
        });
    }
    //选择图片
    public void selectPic() {

        PhotoPicker.builder()
                .setPhotoCount(99)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(false)
                .start(AddCaseActivity.this, PhotoPicker.REQUEST_CODE);

    }

    List<PhotoModel> photosModel = new ArrayList<>();
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK)
            return;
        if (!isdelete) {
            ViseLog.d("新增的图片");
            if (requestCode == PhotoPicker.REQUEST_CODE) {// selected image
                if (data != null && data.getExtras() != null) {
                    ArrayList<String> p = new ArrayList<>();
                    p = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    photosModel.clear();
                    for (int i = 0; i < p.size(); i++) {
                        PhotoModel photoModel = new PhotoModel();
                        photoModel.setOriginalPath(p.get(i));
                        photosModel.add(photoModel);
                    }
                    if (photosModel == null || photosModel.isEmpty()) {
                    } else {
                        ViseLog.d("图片的数据长度" + photosModel.size());
                        minitDatas.addAll(photosModel);
                    }
                    myGrideViewAdapter.notifyDataSetChanged();
                }

            }
        }
    }

    //提交
    @OptionsItem(R.id.action_submit)
    public void action_submit() {

        String msgTitle = et_case_title.getText().toString();
        if (msgTitle.length() == 0) {
            msg("病例标题不能为空");
            return;
        }
        if (HospitalId == 0) {
            msg("请选择医院");
            return;
        }
        String timeDate = tv_time.getText().toString();
        if (timeDate.length() == 0) {
            msg("病例创建时间不能为空");
            return;
        }
        String miaoshu = st_miaoshu.getText().toString();
        if (miaoshu.length() == 0) {
            msg("请添加病例描述");
            return;
        }

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(timeDate);
        stringBuffer.append(" 00:00:00");
        showDialog();

        //修改病例
        if (caseinformationData != null) {
            List<File> fileList = new ArrayList<>();
            for (int i = 0; i < minitDatas.size(); i++) {
                if (!StringUtils.isUrl(minitDatas.get(i).getOriginalPath())) {
                    fileList.add(new File(minitDatas.get(i).getOriginalPath()));
                }
            }
            //如果没有新图片不提交图片
            if (fileList.size() != 0) {
                pictureConstant.PostPicture(fileList);
            } else {
                String url = "";
                List<String> list = new ArrayList<>();
                //循环去除图片头部
                for (int i = 0; i < minitDatas.size(); i++) {
                    list.add(minitDatas.get(i).getOriginalPath().replaceAll(RetrofitConnection.PHOTOURL, ""));
                }
                if (list.size() != 0) {
                    url = photoUrl(list);
                }
                caseHistoryPresenter.UpdatePatientCase(caseinformationData.getId() + "", msgTitle, miaoshu, url, stringBuffer.toString(), HospitalId + "");
            }
        } else {
            if (minitDatas.size() != 0) {
                subPhoto();
            } else {
                caseHistoryPresenter.AddPatientCaseHistoryData(HospitalId + "", msgTitle, miaoshu, stringBuffer.toString(), "");
            }
        }
    }

    //将集合转换成字符
    public String photoUrl(List<String> list) {
        String datas = "";
        HashSet<String> joblist = new HashSet<String>();

        for (int i = 0; i < list.size(); i++) {
            joblist.add(list.get(i));
        }
        if (joblist != null && joblist.size() != 0) {

            Iterator<String> iterator = joblist.iterator();
            while (iterator.hasNext()) {
                datas += iterator.next() + ",";
            }
            datas = datas.substring(0, datas.length() - 1);
        }
        return datas;
    }


    public void subPhoto() {
        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < minitDatas.size(); i++) {
            fileList.add(new File(minitDatas.get(i).getOriginalPath()));
        }
        ViseLog.d("图片的长度" + fileList.size());
        pictureConstant.PostPicture(fileList);
    }

    @Override
    protected void initData() {
        //标题
        if (caseinformationData != null) {
            if (caseinformationData.getTitle() != null && caseinformationData.getTitle().length() > 0) {
                et_case_title.setText(caseinformationData.getTitle());
            }
            //医院名称
            if (caseinformationData.getHospitalId() != 0) {
                for (int i = 0; i < hospitalInfoDBList.size(); i++) {
                    if (hospitalInfoDBList.get(i).getPrimaryid() == caseinformationData.getHospitalId()) {
                        tv_hospital_title.setText(hospitalInfoDBList.get(i).getName());
                        HospitalId = caseinformationData.getHospitalId();
                        break;
                    }
                }
            }
            //病例创建时间
            if (caseinformationData.getLogTime() != null) {
                tv_time.setText(caseinformationData.getMrdateTime().substring(0, 10));
            }
            //描述信息
            if (caseinformationData.getDescription() != null) {
                st_miaoshu.setText(caseinformationData.getDescription());
            }

            if (caseinformationData.getPatientCaseHistoryDetail() != null) {
                if (caseinformationData.getPatientCaseHistoryDetail().getCover() != null && caseinformationData.getPatientCaseHistoryDetail().getCover().length() > 0) {

                    if (caseinformationData.getPatientCaseHistoryDetail().getCover().indexOf(",") == -1) {
                        minitDatas.add(new PhotoModel(RetrofitConnection.PHOTOURL + caseinformationData.getPatientCaseHistoryDetail().getCover()));
                    } else {
                        String[] cover = caseinformationData.getPatientCaseHistoryDetail().getCover().split(",");
                        for (int i = 0; i <= cover.length - 1; i++) {
                            minitDatas.add(new PhotoModel(RetrofitConnection.PHOTOURL + cover[i]));
                        }
                    }
                }
                myGrideViewAdapter.notifyDataSetChanged();
            }
        }


    }

    //医院选择
    @Click(R.id.ll_hospital)
    public void ll_hospital() {
        ShowPickerView();
    }

    //根据省市信息获取医院
    public void screenHospital() {
        Geography.clear();
        Geography.addAll(MainAppliaction.getInstance().Geography());
        int num = Geography.size();
        int size = hospitalInfoDBList.size();
        for (int i = 0; i < num; i++) {
            ArrayList<HospitalInfodb> options1 = new ArrayList<>();
            for (int z = 0; z < size; z++) {

                if (Geography.get(i).getPrimary() == hospitalInfoDBList.get(z).getProvinceID()) {
                    options1.add(hospitalInfoDBList.get(z));
                }
            }
            screenHospitalList.add(options1);
        }
    }

    private void ShowPickerView() {// 弹出选择器
        screenHospital();
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tv_hospital_title.setText(screenHospitalList.get(options1).get(options2).getName());
                HospitalId = screenHospitalList.get(options1).get(options2).getPrimaryid();
            }
        })

                .setTitleText("医院选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        pvOptions.setPicker(Geography, screenHospitalList);//三级选择器  ,screenHospitalList
        pvOptions.show();
    }

    //病例时间
    @Click(R.id.ll_time)
    public void ll_time() {
        //选择手术日期
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int i, int i2, int i3) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, i);
                calendar.set(Calendar.MONTH, i2);
                calendar.set(Calendar.DAY_OF_MONTH, i3);

                tv_time.setText("" + TimeZoneUtil.sdf.format(calendar.getTime()).substring(0, 10));
            }
        }, year, month, day);
        DatePicker datePicker = datePickerDialog.getDatePicker();
        datePicker.setMaxDate(TimeZoneUtil.getStringToDate(TimeZoneUtil.sdf.format(new Date()), "yyyy-MM-dd"));

        datePickerDialog.setTitle("选择病例创建时间");
        datePickerDialog.show();
    }

    @Override
    public void onListSuccess(AnotherResult<CaseinformationData> data) {

    }

    @Override
    public void onSubmitSuccess(DataStateResult data) {
        if (data.getMsgCode().equals("0x00000000")) {
            msg("提交成功");
            dessDialog();
            UpdateEvent updateEvent = new UpdateEvent();
            updateEvent.type = ConstantManger.CASELIST;
            EventBus.getDefault().post(updateEvent);
            finish();
        }
    }

    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
        }
        dessDialog();
    }

    @Override
    public void onRefreshUI() {

    }

    @Override
    public void onDeleteCase(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            msg("提交成功");
            dessDialog();
            UpdateEvent updateEvent = new UpdateEvent();
            updateEvent.type = ConstantManger.CASELIST;
            EventBus.getDefault().post(updateEvent);
            finish();
        }
    }

    @Override
    public void onUpdateCase(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            msg("提交成功");
            dessDialog();
            UpdateEvent updateEvent = new UpdateEvent();
            updateEvent.type = ConstantManger.CASELIST;
            EventBus.getDefault().post(updateEvent);
            finish();
        }
    }

    @Override
    public void updateInit(String path) {

        String msgTitle = et_case_title.getText().toString();
        if (msgTitle.length() == 0) {
            msg("病例标题不能为空");
            return;
        }
        if (HospitalId == 0) {
            msg("请选择医院");
            return;
        }
        String timeDate = tv_time.getText().toString();
        if (timeDate.length() == 0) {
            msg("病例创建时间不能为空");
            return;
        }
        String miaoshu = st_miaoshu.getText().toString();
        if (miaoshu.length() == 0) {
            msg("请添加病例描述");
            return;
        }

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(timeDate);
        stringBuffer.append(" 00:00:00");

        //如果是修改
        if (caseinformationData != null) {
            StringBuffer stringBuffer1 = new StringBuffer();
            String url = "";
            //如果不全是网络数据
            List<String> list = new ArrayList<>();
            //循环去除图片头部
            for (int i = 0; i < minitDatas.size(); i++) {
                if (StringUtils.isUrl(minitDatas.get(i).getOriginalPath())) {
                    list.add(minitDatas.get(i).getOriginalPath().replaceAll(RetrofitConnection.PHOTOURL, ""));
                }
            }
            if (list.size() != 0) {
                url = photoUrl(list);
            }

            //和新加的图片进行拼接
            if (url.length() > 0) {
                stringBuffer1.append(url+"," + path);
            } else {
                stringBuffer1.append(path);
            }
            caseHistoryPresenter.UpdatePatientCase(caseinformationData.getId() + "", msgTitle, miaoshu, stringBuffer1.toString(), stringBuffer.toString(), HospitalId + "");
        } else {
            caseHistoryPresenter.AddPatientCaseHistoryData(HospitalId + "", msgTitle, miaoshu, stringBuffer.toString(), path);
        }
    }

    @Override
    public void onErrPhoto(String errVal) {

        if (errVal != null) {
            msg(errVal);
        }
        dessDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        minitDatas.clear();
        EventBus.getDefault().unregister(this);
    }

    boolean isdelete = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DeletePhotoEvent deletePhotoEvent) {
        isdelete = true;
        ViseLog.d("删除下标为" + deletePhotoEvent.photoId + "的图片");
        minitDatas.remove(deletePhotoEvent.photoId);
        myGrideViewAdapter.notifyDataSetChanged();
    }
}
